package com.example.demo.common.web;

import com.example.demo.account.entity.*;
import com.example.demo.account.service.UserRoleService;
import com.example.demo.account.service.impl.ResourceServiceImpl;
import com.example.demo.account.service.impl.UserServiceImpl;
import com.example.demo.common.utils.CheckMobile;
import com.example.demo.common.utils.Constant;
import com.example.demo.common.utils.SpringSecurityUtils;
import com.example.demo.information.entity.Photo;
import com.example.demo.information.entity.Student;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.information.service.PhotoService;
import com.example.demo.information.service.StudentService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 描述：
 *
 * @author littlecar
 * @date 2019/9/4 14:50
 */
@Controller
/*@Api(value = "/indexOfmain",description = "Operations about index")*/
public class IndexController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ResourceServiceImpl resourceService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private PhotoService photoService;

    @RequestMapping("/index")
    public String index(HttpServletRequest request,ModelMap map) {
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        currentUserDetails.setLgType(CheckMobile.check(request.getHeader("User-Agent"))?"1":"0");
        System.out.println(currentUserDetails.getLgType()+"@@@@@@");
        SysUserRole role = userRoleService.findById(currentUserDetails.getCurrUserRoleId());
        if("1".equals(currentUserDetails.getLgType())&&role.getRole_id()== Constant.STUDENT_ID){
            Student student = studentService.findBySfz(currentUserDetails.getUsername());
            map.addAttribute("studentInfo", new StudentInfo(student));
            //TODO 可以考虑是否放到前端加载
            Photo photo= photoService.findByXsxxIdAndXxxxIdAndBjxxId(student.getId()
                    ,student.getSchool().getId(),student.getBjxx().getId());
            if(photo!=null){
                map.addAttribute("address",photo.getId());
            }
            return "mobile/stuIndexMob";
        }else{
            return "index";
        }
    }

    @RequestMapping("/toChooseRole")
    public String toChooseRole(ModelMap map,HttpServletRequest request) {
        String password = request.getParameter("password");
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        currentUserDetails.setUserPwd(password);
        request.getSession().setAttribute("user",currentUserDetails);
        Set<SysUserRole> sysUserRoles = currentUserDetails.getSysUserRoles();
        Map<Long,String> userRoleMap=userRoleService.combineUserRoles(Lists.newArrayList(sysUserRoles));
        map.addAttribute("userRoleMap", userRoleMap);
        return "chooseRole";
    }
    @GetMapping("/chooseRole/{userRoleId}")
    public String toChooseRole(@PathVariable("userRoleId") Long userRoleId,HttpServletRequest request) {
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        SecurityUser su = (SecurityUser) request.getSession().getAttribute("user");
        if (currentUserDetails.getUserPwd()== null) {
            currentUserDetails.setUserPwd(su.getUserPwd());
        }
        currentUserDetails.setCurrUserRoleId(userRoleId);
        request=userService.doRoleChoose(userRoleId,request,currentUserDetails);
        return "redirect:/index";
    }

    @RequestMapping("/getUserName")
    @ResponseBody
    public String getUserName() {
        return SpringSecurityUtils.getCurrentUserDetails().getName();
    }
    @GetMapping("/login")
    public String login(HttpServletRequest request)
    {
        int type = 0;
        if(CheckMobile.check(request.getHeader("User-Agent"))){
            type = 1;
        }
        if(type==1){
            return "mobile/mobLogin";
        }else{
            return "login";
        }
    }

    @RequestMapping("/403")
    public String error() {
        return "error/403";
    }

    @RequestMapping("/admin")
    @ResponseBody
    public String admin() {
        return "admin";
    }

    @RequestMapping("/user")
    @ResponseBody
    public String user() {
        return "user";
    }

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    @RequestMapping("/main")
    public String main(HttpServletResponse response) {
        response.addHeader("x-frame-options","SAMEORIGIN");
        return "main";
    }

    @RequestMapping("/getRes")
    @ResponseBody
    public Map<String, List<ResourceInfo>> getRes(HttpServletRequest request) {
        Map<String, List<ResourceInfo>> map = new HashMap<>();
        Long userRoleId = SpringSecurityUtils.getCurrentUserRoleId();
        SysUserRole userRole = userRoleService.findById(userRoleId);
        List<SysResource> resourceList=resourceService.findResourceByRoleId(userRole.getRole_id());
        List<ResourceInfo> resourceInfos = resourceService.combineJson(resourceList);
        map.put("contentManagement",resourceInfos);
        return map;
    }

    @RequestMapping("/getRoles")
    @ResponseBody
    public Map<String,String> getRoles() {
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        Long user_id = currentUserDetails.getId();
        System.out.println(user_id);
        List<SysUserRole> sysUserRoles = userRoleService.findByUserId(user_id);
//        Set<SysUserRole> sysUserRoles = currentUserDetails.getSysUserRoles();
        Map<Long,String> userRoleMap=userRoleService.combineUserRoles(sysUserRoles);
        Set<Map.Entry<Long, String>> entries = userRoleMap.entrySet();
        String html="";
        html += "<form class=\"layui-form\" style=\"height: 360px\">\n" +
                "\t\t<div class=\"layui-form-item\" style=\"text-align: center\">";
        for (Map.Entry<Long, String> entry:
                entries) {
            html += "<a class=\"layui-btn layui-block\" " +
                    "style=\"margin-left: 0px;margin-top: 10px;width: 70% !important; \" " +
                    "href=\"/chooseRole/"+entry.getKey()+"\" >" +
                    " "+entry.getValue()+"</a>";
        }
        html += "</div>";
        html += "</form>";
        Map<String,String> map= Maps.newLinkedHashMap();
        map.put("html", html);
        return map;

    }
}
